import {createRouter,createWebHistory,createWebHashHistory} from 'vue-router'

import doRequire from "../axios.js"
import home from "../home.vue"
import login from "../login.vue"

const routes =[
    //路由的默认路径
    {
       
        path:"/",
        redirect:"/login",
        meta:{isAuthorities:true}, 
    },
    {
        name:"login",
        path:'/login',
        component:login,
        meta:{isAuthorities:false,title:"登录"},  
       
    },
            {
                name:'home',
                path:'/home',
                component:home,
                meta:{isAuthorities:true,title:"主页"},
            }
        
  
]

const router =createRouter({
   history:createWebHistory(),
    routes
})

//全局守卫 
//在暴露之前，加上前置路由守卫
 router.beforeEach((to,from,next) => {
 if(to.meta.isAuthorities){//需要认证
    if(!localStorage.getItem("userTokenStatus")=='ok'){
        ElMessage.error("请重新完成登录哦~");
    }

     //每次访问home，发送请求，如果token正常，就放行，否则就跳会login
     doRequire("http://localhost:8080/home").then(res=>{
          localStorage.setItem("userTokenStatus",res.data.msg);
          next();
    })

}
else{//不需要认证就直接放行认证
    next();
}
})

//后置路由守卫
router.afterEach((to,from) => {

     document.title=to.meta.title;
})

//导出
export default router;